from json import loads, dumps
from requests import post, get
from log import err, out
from time import time
from common import make_verify_sign, now, hwinfo
from config import SECRET_KEY, REGISTER_URL
from exec import run_cmd


def center_post(**data):
    keys = data.keys()

    action = '' if 'action' not in keys else data.pop('action')

    if 'sign' not in keys:
        data['sign'] = make_verify_sign(data, None, 'CenterRegister', SECRET_KEY)
    if 'times' not in keys:
        data['times'] = int(time())

    #  print('Center Server Post(%s): %s' % (action, data))
    try:
        r = post("%s%s" % (REGISTER_URL, action), data)
        result = loads(r.text)
        result['request'] = data
    except Exception as e:
        err('蚁穴通信错误: ', stack=True)
        result = {'code': 9999, 'msg': e}

    return result

def push_log(title, content=''):
    content = "%s: %s" % (now(), content)
    return center_post(action='/log', title=title, content=content)

def get_version():
    try:
        f = open('./version', 'r')
        version = loads(f.read())
        f.close()
        return version
    except Exception as e:
        err('获取版本错误: ', stack=True)

    return None

def app_auto_update():
    version = get_version()
    if version is None:
        version = {'version': 0}
    u = center_post(action='/update', **version, **hwinfo())
    out("Auto Update Post: ", u)
    if not u['code']:
        return None
    try:
        runfile = '/tmp/update.sh'
        r = get(u['url'])
        r.raise_for_status()
        f = open(runfile, 'wb')
        f.write(r.content)
        f.close()
        out('Auto Update Run: ', run_cmd("/bin/bash %s" % runfile))
    except Exception as e:
        err('蚂蚁自动更新错误: ', stack=True)

